/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package blms.domain;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import blms.domain.Expression.Context;

/**
 * 
 * @author João Arthur
 * @author Jonhnny Weslley
 * @author Thiago Emmanuel
 * @version 1.00, 25/04/2008
 * @since 1.0
 */
public class MapContextAdapter implements Context {

	private final Map<String, Integer> context;

	/**
	 * Creates a new MapContextAdapter.
	 */
	public MapContextAdapter() {
		this(new HashMap<String, Integer>());
	}

	/**
	 * Creates a new MapContextAdapter with the given context.
	 */
	public MapContextAdapter(final Map<String, Integer> context) {
		if (context == null) {
			throw new IllegalArgumentException();
		}
		this.context = context;
	}

	/**
	 * Returns the variable related to the specified name.
	 */
	public int getVariable(final String name) {
		return context.get(name);
	}

	/**
	 * Returns the available variables.
	 */
	public Set<String> getAvailableVariables() {
		return context.keySet();
	}

	/**
	 * Adds a new variable with the specified name and value.
	 * 
	 * @param name
	 *            the name of the new variable.
	 * @param value
	 *            the value of the new variable.
	 */
	public void setVariable(final String name, final Integer value) {
		if (value != null) {
			context.put(name, value);
		}
	}

	/**
	 * Adds a new variable.
	 * 
	 * @param name
	 *            the name of the new variable.
	 * @param value
	 *            the value of the new variable.
	 * @return this <code>MapContextAdapter</code>
	 */
	public MapContextAdapter set(final String name, final Integer value) {
		if (value == null) {
			context.remove(name);

		} else {
			context.put(name, value);
		}
		return this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return context.toString();
	}

}